package dbPhase.hypeerweb;
/**
 * FoldRole extends Connection and overrides all the methods to change the connections
 * in reference as a fold.
 *
 * @see Connection
 *
 *
 * @author scott44
 *
 */
public class FoldRole extends Connection {
	public FoldRole(Node n, Node b) {
		super(n, b);
	}

	@Override
	public void addConnection(Node add) {
		if (delegate.fold != Null_Node.getSingleton()) {
			delegate.inverseSurrogateFold = delegate.fold;
			delegate.fold = add;
		}
		else {
			delegate.fold = add;
			delegate.surrogateFold = Null_Node.getSingleton();
		}

		if (delegate.nodeState == HypercubeCapState.getSingleton()) {
			delegate.nodeState = StandardNodeState.getSingleton();
		}
	}

	@Override
	public void removeConnection(Node remove) {
		if (delegate.inverseSurrogateFold != Null_Node.getSingleton()) {
			delegate.fold = delegate.inverseSurrogateFold;
			delegate.inverseSurrogateFold = Null_Node.getSingleton();
			sourceParent.fold = delegate;
			sourceParent.surrogateFold = Null_Node.getSingleton();
			remove.fold = Null_Node.getSingleton();
		}
		else if (delegate.fold != Null_Node.getSingleton()) {
			delegate.surrogateFold = sourceParent;
			delegate.fold = Null_Node.getSingleton();
			remove.fold = Null_Node.getSingleton();
			sourceParent.inverseSurrogateFold = delegate;
		}

		if ((delegate.fold.getWebIdValue() == 0) && delegate.getBiggestUpPointer() == Null_Node.getSingleton()) {
			delegate.nodeState = HypercubeCapState.getSingleton();
		}

		if (delegate.getWebIdValue() == 0 && delegate.neighbors.size() == 0 &&
				delegate.downPointers.size() == 0 && delegate.upPointers.size() == 0) {
			delegate.fold = delegate;
			delegate.inverseSurrogateFold = Node.NULL_NODE;
			delegate.surrogateFold = Node.NULL_NODE;
			delegate.nodeState = HypercubeCapState.getSingleton();
		}
	}

	@Override
	public void replaceConnection(Node oldNode, Node newNode) {

		if (delegate.fold != Null_Node.getSingleton()) {
			delegate.fold = newNode;
			newNode.fold = delegate;
		}
		oldNode.surrogateFold = Null_Node.getSingleton();
		oldNode.inverseSurrogateFold = Null_Node.getSingleton();
		oldNode.fold = Null_Node.getSingleton();
	}
}
